package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"github.com/gorilla/websocket"
	"log"
	"weekFirst/global"
	"weekFirst/pkg"
)

type ChatController struct {
	beego.Controller
}

func (c *ChatController) ChatIm() {
	userId := c.GetString("user_id")

	var auth = true
	if auth {
		auth = true
	}

	var upgrader = websocket.Upgrader{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
	}

	conn, err := upgrader.Upgrade(c.Ctx.ResponseWriter, c.Ctx.Request, nil)
	if err != nil {
		log.Println(err)
		return
	}

	node := global.Node{
		Conn: conn,
		Data: make(chan []byte, 50),
	}

	global.ClientMap[userId] = node

	//协程
	go GetMessage(node)
	go SetMessage(node)

	c.Data["json"] = global.Response{
		Code:    0,
		Message: "私聊创建ok",
		Data:    nil,
	}

	c.ServeJSON()
}

func GetMessage(node global.Node) {
	for {
		_, message, err := node.Conn.ReadMessage()
		if err != nil {
			return
		}

		var msg global.Message

		json.Unmarshal(message, &msg)

		if !pkg.TextCheck(msg.Message) {
			exam := global.TextExam{
				Context:     "输入内容不合规",
				MessageType: "2",
			}

			marshal, _ := json.Marshal(exam)

			global.ClientMap[msg.ObjId].Data <- marshal
		} else {
			if data, ok := global.ClientMap[msg.ObjId]; ok {
				data.Data <- message
			}
		}

	}
}

func SetMessage(node global.Node) {
	for {
		data, ok := <-node.Data

		if ok {
			node.Conn.WriteMessage(websocket.TextMessage, data)
		}
	}
}
